package cases

import (
  "context"
  "go.mongodb.org/mongo-driver/bson"
  "go.mongodb.org/mongo-driver/bson/primitive"
  "go.mongodb.org/mongo-driver/mongo/options"
  "livefind/db"
  "livefind/utils/logger"
)

type CaseModel struct {
}

type CaseInfo struct {
  ID          primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
  CaseNo      string             `json:"caseNo,omitempty" bson:"caseNo,omitempty"`
  CaseName    string             `json:"caseName,omitempty" bson:"caseName,omitempty"`
  CreateTime  int64              `json:"createTime,omitempty" bson:"createTime,omitempty"`
  Creator     string             `json:"creator,omitempty" bson:"creator,omitempty"`
  Description string             `json:"description,omitempty" bson:"description,omitempty"`
  CaseType    string             `json:"caseType,omitempty" bson:"caseType,omitempty"`
  Inquisitor  []string           `json:"inquisitor,omitempty" bson:"inquisitor,omitempty"`
}

func (cm *CaseModel) FindCaseByFilter(filter bson.M) (caseInfo CaseInfo, err error) {
  CaseMongo := db.Collection("cases", "case")

  ctx := context.TODO()
  err = CaseMongo.FindOne(ctx, filter).Decode(&caseInfo)

  return caseInfo, err
}

func (cm *CaseModel) Create(info CaseInfo) (err error) {
  caseMongo := db.Collection("cases", "case")

  ctx := context.TODO()
  _, err = caseMongo.InsertOne(ctx, &info)

  if err != nil {
    logger.Error(err.Error(), err)
  }
  return err
}

func (cm *CaseModel) List(filter bson.M, sorted bson.D, skip, limit int) (casesInfo []CaseInfo, err error) {
  caseMongo := db.Collection("cases", "case")

  ctx := context.TODO()
  opts := options.Find()
  opts.SetSort(sorted)
  opts.SetSkip(int64(skip))
  opts.SetLimit(int64(limit))
  casesInfoCursor, err := caseMongo.Find(ctx, filter, opts)

  defer func() { _ = casesInfoCursor.Close(ctx) }()

  if err != nil {
    logger.Error(err.Error(), err)
    return nil, err
  }
  if err = casesInfoCursor.All(ctx, &casesInfo); err != nil {
    logger.Error(err.Error(), err)
    return nil, err
  }
  return casesInfo, err
}

func (cm *CaseModel) CountDocuments(filter bson.M) (totalNum int64, err error) {
  caseMongo := db.Collection("cases", "case")

  ctx := context.TODO()
  totalNum, err = caseMongo.CountDocuments(ctx, filter)

  if err != nil {
    logger.Error(err.Error(), err)
    return 0, err
  }
  return totalNum, err
}

func (cm *CaseModel) GetById(filter bson.M) (caseInfo CaseInfo, err error) {
  caseMongo := db.Collection("cases", "case")

  ctx := context.TODO()
  err = caseMongo.FindOne(ctx, filter).Decode(&caseInfo)

  if err != nil {
    logger.Error(err.Error(), err)
    return CaseInfo{}, err
  }
  return caseInfo, err
}
